package institution

import (
	"feng-che.com/server/driver-quiz/internal/sysLogger"
	serverCommon "fiberCommonUtils/common"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"mongoDB"
	"time"
)

var cacheInstitution InstitutionList

func ReadPublicInstitutionInCache() InstitutionList {
	if cacheInstitution == nil {
		return InstitutionList{}
	}
	return cacheInstitution
}

func CacheAllInstitution() {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	result := InstitutionList{}
	err := result.FindMany(ctx, &bson.D{
		*mongoDB.CommonFilterNotDeleted(),
	})
	if err != nil {
		sysLogger.SysLog.WithFields(logrus.Fields{
			"err":          err.Error(),
			"databaseName": (&Institution{}).GetCollection().Database().Name(),
		}).Warn("缓存服务失败")
		time.Sleep(1 * time.Minute)
		CacheAllInstitution()
		return
	}
	cacheInstitution = result
	time.Sleep(1 * time.Minute)
	CacheAllInstitution()
}

func RequestInstitutionInCache(c *fiber.Ctx) error {
	return c.JSON(serverCommon.MakeSuccessJson(ReadPublicInstitutionInCache()))
}

// CacheDataOfVehicle 缓存车辆信息，根据id查找
var CacheDataOfVehicle map[primitive.ObjectID]Vehicle

func CacheAllVehicles() {
	if CacheDataOfVehicle == nil {
		CacheDataOfVehicle = make(map[primitive.ObjectID]Vehicle)
	}
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	result := VehicleList{}
	err := result.FindMany(ctx, &bson.D{
		*mongoDB.CommonFilterNotDeleted(),
	})
	if err != nil {
		sysLogger.SysLog.WithFields(logrus.Fields{
			"err":          err.Error(),
			"databaseName": (&Institution{}).GetCollection().Database().Name(),
		}).Warn("缓存服务失败")
		time.Sleep(5 * time.Minute)
		CacheAllVehicles()
		return
	}
	for _, vehicle := range result {
		CacheDataOfVehicle[vehicle.ID] = vehicle
	}
	time.Sleep(5 * time.Minute)
	CacheAllVehicles()
}
